package com.wlts.wzy.KSOrderModule.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.linkedmall.model.v20180116.EnableOrderRequest;
import com.aliyuncs.linkedmall.model.v20180116.EnableOrderResponse;
import com.aliyuncs.linkedmall.model.v20180116.QueryOrderListRequest;
import com.aliyuncs.linkedmall.model.v20180116.QueryOrderListResponse;
import com.wlts.wzy.KSOrderModule.entity.KsOrders;
import com.wlts.wzy.KSOrderModule.service.IKsOrdersService;
import com.wlts.wzy.KSUserModule.entity.KsStoreUser;
import com.wlts.wzy.KSUserModule.service.IKsStoreUserService;
import com.wlts.wzy.LMGoodsModule.service.ILmAddressService;
import com.wlts.wzy.LMGoodsModule.service.ILmSelfGoodsService;
import com.wlts.wzy.configBean.LmConfig.LmConfig;
import com.wlts.wzy.expand.MyLambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.*;
import java.util.stream.Collectors;

import static com.wlts.wzy.configBean.LmConfig.LmConfig.client;

@Component
public class LmUpdateOrdersToLocalUtil {
    @Autowired
    private IKsOrdersService ksOrdersService;
    @Autowired
    private ILmSelfGoodsService lmSelfGoodsService;
    @Autowired
    private ILmAddressService lmAddressService;
    @Autowired
    private IKsStoreUserService ksStoreUserService;

    /**
     * 获得发货订单--更新订单
     */
    @Scheduled(fixedDelay = 211 * 1000)
//    @PostConstruct
    public void LmUpdateOrdersToLocal() throws ClientException {

        MyLambdaQueryWrapper<KsStoreUser> userWrapper = new MyLambdaQueryWrapper<>();

        userWrapper.eq(KsStoreUser::getDelFlag, "0");

        userWrapper.isNotNull(KsStoreUser::getKsSellerId);

        List<KsStoreUser> ksOauthList = ksStoreUserService.list(userWrapper);

        for (KsStoreUser user : ksOauthList
        ) {
            MyLambdaQueryWrapper<KsOrders> queryWrapper = new MyLambdaQueryWrapper<>();

            queryWrapper.in(KsOrders::getSelfOrder, 1);//平台商品的订单 0未确定 1是 2不是

            queryWrapper.eq(KsOrders::getPutLmStatus, 1);//推送lm状态 0未推送 1已推送 2推送失败

            queryWrapper.eq(KsOrders::getStatus, 30);

            queryWrapper.eq(KsOrders::getSellerId, user.getKsSellerId());

            queryWrapper.eq(KsOrders::getSendStatus, 0);

            queryWrapper.isNotNull(KsOrders::getLmOrderId);

            int page = 1;
            int pageSize = 15;

            while (true) {

                List<KsOrders> ksOrdersList = ksOrdersService.page(queryWrapper, page, pageSize, true).getRecords();

//                System.out.println("这是需要更新状态订单-----");
//                System.out.println(ksOrdersList.toString());
//                System.out.println("这是需要更新状态订单-----");

                if (ksOrdersList.size() > 0) {

                    Set<String> oidset = ksOrdersList.stream().map(KsOrders::getLmOrderId).filter(Objects::nonNull).collect(Collectors.toSet());

                    Map<String, KsOrders> map = ksOrdersList.stream().collect(Collectors.toMap(KsOrders::getLmOrderId, a -> a, (a, o) -> a));

                    QueryOrderListRequest request = new QueryOrderListRequest();
                    request.setBizId(LmConfig.LZ_BIZ_ID);
                    request.setAccountType("ANONY");
                    request.setThirdPartyUserId(user.getKsSellerId() + "");
                    request.setBizUid(request.getThirdPartyUserId());
                    request.setPageSize(10L);
                    request.setPageNumber(1L);
                    JSONObject filterOption = new JSONObject();
                    filterOption.put("orderStatus", 2);//"orderStatus":"12=待⽀付，2=已⽀付，4=已退款关闭，6=交易成功，8=被淘宝 关闭 ",
                    filterOption.put("logisticsStatus", 2);//1=未发货 -> 等待卖家发货 2=已发货 -> 等待买家确 认收货 3=已收货 -> 交易成功 4=已经退货 -> 交易失败 5=部分收货 -> 交易成功 6= 部分发货中 8=还未创建物流订单"
                    filterOption.put("enableStatus", 0);
                    filterOption.put("lmOrderList", oidset);
                    request.setFilterOption(filterOption.toJSONString());

                    QueryOrderListResponse response = client.getAcsResponse(request);

                  //  System.out.println(JSON.toJSONString(response));

                    List<QueryOrderListResponse.LmOrderListItem> lmOrderList = response.getLmOrderList();

                    lmOrderList.forEach(lmOrderListItem -> {

                        String lmOrderId = lmOrderListItem.getLmOrderId() + "";

                        KsOrders orders = map.get(lmOrderId);
                        if (orders != null) {
                            orders.setSendStatus(1);
                            ksOrdersService.updateById(orders);
                        }
                    });
                }
                if (ksOrdersList.size() < pageSize) {
                    break;
                }
                page += 1;
            }
        }

    }

    public static void main(String[] args) throws ClientException {
        Set<String> oidset=new HashSet<>();

        oidset.add("2105800043964312");

        QueryOrderListRequest request = new QueryOrderListRequest();
        request.setBizId(LmConfig.LZ_BIZ_ID);
        request.setAccountType("ANONY");
        request.setThirdPartyUserId("2117889290");
        request.setBizUid(request.getThirdPartyUserId());
        request.setPageSize(10L);
        request.setPageNumber(1L);
        JSONObject filterOption = new JSONObject();

//        filterOption.put("orderStatus", 2);//"orderStatus":"12=待⽀付，2=已⽀付，4=已退款关闭，6=交易成功，8=被淘宝 关闭 ",
//        filterOption.put("logisticsStatus", 2);//1=未发货 -> 等待卖家发货 2=已发货 -> 等待买家确 认收货 3=已收货 -> 交易成功 4=已经退货 -> 交易失败 5=部分收货 -> 交易成功 6= 部分发货中 8=还未创建物流订单"
//        filterOption.put("enableStatus", 0);
//        filterOption.put("lmOrderList", oidset);
        filterOption.put("channelOrderIdList", oidset);
        request.setFilterOption(filterOption.toJSONString());
        QueryOrderListResponse response = client.getAcsResponse(request);
        System.out.println(JSON.toJSONString(response));


 //       enableOrder("2105100005708710","264243418");

    }

    /**
     * 支付订单
     *
     * @return
     */
    public static EnableOrderResponse enableOrder(String outOrderId, String lmOrderId) {

        //{"code":"SUCCESS","logsId":"","message":"操作成功，但是创建支付单失败，请到订单列表点击继续支付。","model":{"lmOrderList":[{"lmOrderId":"243467676"}],"orderIds":["1541205903044906332"],"payTradeIds":[],"redirectUrl":"https://pages.tmall.com/wow/wt/act/lm-pages?wh_page=order-list"},"requestId":"0B2A116C-BD1A-4467-B68C-4783D163F0A8","subCode":"","subMessage":"","success":true}
        EnableOrderRequest request = new EnableOrderRequest();
        request.setBizId(LmConfig.LZ_BIZ_ID);
        request.setAccountType("ANONY");
        request.setThirdPartyUserId("2117889290");
        request.setBizUid(request.getThirdPartyUserId());
        request.setLmOrderId(lmOrderId);
        request.setOutTradeId(outOrderId);
//        request.setItemId(itemId);
//        //  request.setPageSize(10);

        try {
            EnableOrderResponse resp = client.getAcsResponse(request);

            System.out.println(JSON.toJSONString(resp));

            //{"code":"WITHHOLD_RESULT_STATUS_UNKOWN","logsId":"","message":"RESULT_STATUS_UNKOWN","model":{"lmOrderList":[],"orderIds":[],"payTradeIds":[],"redirectUrl":"RESULT_STATUS_UNKOWN"},"requestId":"B1AC36AC-903D-47EB-839A-A7AA442979A4","subCode":"","subMessage":"","success":true}
            return resp;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }




}
